package com.ebupt.migu.music.global.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ebupt.migu.globalpopup.entity.ActionType;
import com.ebupt.migu.globalpopup.entity.ActivityInfo;
import com.ebupt.migu.globalpopup.enums.FileTypeEnum;
import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.global.mapper.ActionTypeMapper;
import com.ebupt.migu.music.global.mapper.ActivityInfoMapper;
import com.ebupt.migu.music.global.service.GlobalFileService;
import com.ebupt.migu.music.global.utils.TxtUtil;
import com.ebupt.migu.music.global.vo.ActionTypeVO;
import com.ebupt.migu.music.redis.service.RedisService;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author liuyangyang@ebupt.com
 * @Description
 * @Date 2021/11/23 10:07
 */
@Service
@Slf4j
public class GlobalFileServiceImpl implements GlobalFileService {

    @Resource
    private ActionTypeMapper actionTypeMapper;

    @Resource
    private ActivityInfoMapper activityInfoMapper;

    @Resource
    private RedisService redisService;

    // 文件默认保存路径
    @Value("${path.file_global_path}")
    private String FILE_GLOBAL_PATH;

    // 文件默认保存路径
    @Value("${globla-sys.ip}")
    private String IP;

    @Override
    public ResultObject getlist() {
        ResultObject resultObject = new ResultObject();
        List<ActionTypeVO> actionTypeVOList = new ArrayList<>();
        List<ActionType> actionTypes = actionTypeMapper.selectList(new QueryWrapper<ActionType>()
                .lambda()
                .eq(true, ActionType::getActionStatus, 1));
        if (!actionTypes.isEmpty()) {
            actionTypeVOList = actionTypes
                    .stream()
                    .map(actionType -> {
                        ActionTypeVO actionTypeVO = new ActionTypeVO();
                        BeanUtils.copyProperties(actionType, actionTypeVO);
                        return actionTypeVO;
                    }).collect(Collectors.toList());
        }
        resultObject.setCode("0000");
        resultObject.setMsg("操作成功");
        resultObject.setData(actionTypeVOList);
        return resultObject;
    }

    @Override
    public ResultObject isName(String name, String activityId) {
        ResultObject resultObject = new ResultObject();
        ActivityInfo activityInfo = activityInfoMapper.selectOne(new QueryWrapper<ActivityInfo>()
                .lambda()
                .eq(true, ActivityInfo::getActivityName, name)
                .ne(activityId != null && !activityId.equals(""), ActivityInfo::getActivityId, activityId)
        );
        if (activityInfo == null) {
            resultObject.setCode("0000");
            resultObject.setMsg("活动名不存在");
        } else {
            resultObject.setCode("2222");
            resultObject.setMsg("活动名已存在");
        }
        return resultObject;
    }

    @Override
    public ResultObject uploadFile(MultipartFile multipartFile, Integer type) {
        ResultObject resultObject = new ResultObject();
        HashMap<Object, Object> map = new HashMap<>();
        if (multipartFile != null) {
            String originalFilename = multipartFile.getOriginalFilename();
            String path = FILE_GLOBAL_PATH + FileTypeEnum.getCodeByFile(type);
            map.put("fileName", originalFilename);
            log.info("上传文件：{}类型:{}路径：{}", originalFilename, type, path);
            String filePath = path + "/" + originalFilename;
            try {
//                 filePath = "D:\\apps\\fine-operation-label\\" + originalFilename; // 本地测试
                File file = new File(filePath);
                multipartFile.transferTo(file);
                // 将文件存到redis
                TxtUtil txtUtil = TxtUtil.getTxtUtil();
                List list = txtUtil.toList(file);
                Set set = new HashSet<>(list);
//                redisService.setSet(filePath, set);
                redisService.setManyValueSet(filePath, set);
                map.put("fileSize",list.size());
            } catch (IllegalStateException e) {
                e.printStackTrace();
                log.info("上传文件：{}失败:{}", originalFilename, e);
                resultObject.setCode("1111");
                resultObject.setMsg("上传失败");
                File file = new File(filePath);
                if (file.isFile() && file.exists()) {
                    file.delete();
                }
                return resultObject;
            } catch (IOException e) {
                e.printStackTrace();
                log.info("上传文件：{}失败:{}", originalFilename, e);
                resultObject.setCode("1111");
                resultObject.setMsg("上传失败");
                File file = new File(filePath);
                if (file.isFile() && file.exists()) {
                    file.delete();
                }
                return resultObject;
            }catch (Exception e){
                e.printStackTrace();
                log.info("上传文件：{}失败:{}", originalFilename, e);
                resultObject.setCode("1111");
                resultObject.setMsg("上传失败");
                File file = new File(filePath);
                if (file.isFile() && file.exists()) {
                    file.delete();
                }
                return resultObject;
            }
        }
        resultObject.setCode("0000");
        resultObject.setMsg("操作成功");
        resultObject.setData(map);
        return resultObject;
    }

    @Override
    public ResultObject delFile(String fileName, Integer type) {
        ResultObject resultObject = new ResultObject();
        String filePath = FILE_GLOBAL_PATH + FileTypeEnum.getCodeByFile(type) + "/" + fileName;
        File delFile = new File(FILE_GLOBAL_PATH + FileTypeEnum.getCodeByFile(type), fileName);
        if (delFile.isFile() && delFile.exists()) {
            delFile.delete();
            // 删除redis数据
            redisService.remove(filePath);
            resultObject.setCode("0000");
            resultObject.setMsg("操作成功");
            return resultObject;
        }
        log.info("删除文件：{}失败:{}", fileName);
        resultObject.setCode("1111");
        resultObject.setMsg("操作失败");
        return resultObject;
    }
}
